#include <iostream>
#include <unistd.h>
#include <cstdlib>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;

int main(int argc, char *argv[])
{
    pid_t pid;
    cout << "This is main proces, PID is " << getpid() << endl;

    pid = fork();
    if (pid < 0) {
        cout << "fork error..." << endl;
        exit(-1);
    }
    else if (pid == 0) { //This is the child process
        cout << "This is child process, PID is " << getpid() << endl;
        sleep(3); //子进程休眠3秒, 这样就可以看到wait函数阻塞了父进程, 因为三秒之后, wait语句下面的语句才开始执行
        exit(11); //将子进程的退出码设置为11
    }
    else{
        cout << "This is main process waiting for the exit of child process." << endl;
        int child_status;
        /*
        wait系统调用会使父进程暂停执行, 直到它的等待子进程结束为止。也就是说wait是阻塞的。
        wait可以返回两个信息, 直接返回子进程的PID, 还有status(注意这个值不是在子进程中调用exit函数中的退出码, 下面有专门的宏使用该status), 
        子进程的退出状态信息存放在wait的参数status指向的内存中。
        */
        pid = wait(&child_status);
        cout << "This is main process. The child status is " << child_status << ", and child pid is " << pid << ", WIFEXITED(child_status) is " << WIFEXITED(child_status) << ", WEXITSTATUS(child_status) is " << WEXITSTATUS(child_status) << endl;
    }
    exit(0);
}